package com.teacher.game.state;

import android.graphics.Color;
import android.graphics.Rect;
import android.util.Log;
import android.view.MotionEvent;
import com.teacher.game.framework.util.Painter;
import com.teacher.ellio.Assets;
import com.teacher.ellio.GameMainActivity;
import com.teacher.game.framework.util.UIButton;
import com.teacher.game.framework.util.ScoreManager;
import com.teacher.game.framework.animation.UIAnimations;
import com.teacher.game.framework.animation.AnimationSet;
import com.teacher.game.framework.animation.UIAnimator;
import com.teacher.game.framework.animation.Tween;

/**
 * 主菜单状态 - 增强版，支持统计显示和高级视觉效果
 * 
 * Story 4.1: 主菜单界面优化
 * - 显示游戏统计数据（总游戏次数、最高分记录）
 * - 增强视觉效果（背景渐变、脉动动画、按钮特效）
 * - 流畅的动画过渡和用户体验优化
 * - 集成难度选择和得分界面导航
 * 
 * @version 3.0 - Story 4.1 主菜单界面优化
 * @since 2025-09-12
 */
public class MenuState extends State {
    
    // UI组件
    UIButton playBtn, scoreBtn, settingsBtn;
    
    // 动画管理
    private AnimationSet entranceAnimations;  // 入场动画集合
    private UIAnimator currentClickAnimation;  // 当前点击反馈动画
    private boolean animationsEnabled = true;  // 动画是否启用
    
    // 数据管理
    private ScoreManager scoreManager;         // 得分管理器
    
    // 视觉效果
    private float titlePulse = 0;              // 标题脉动动画
    private float backgroundWave = 0;          // 背景波浪动画
    private float buttonGlow = 0;              // 按钮发光效果
    private boolean showQuickStats = true;     // 是否显示快速统计
    
    // 显示文本
    private String highScoreText = "";         // 最高分文本
    private String totalGamesText = "";        // 总游戏次数文本
    private String playerLevelText = "";       // 玩家等级文本
    private String welcomeMessage = "";        // 欢迎信息

    @Override
    public void init() {
        // 初始化得分管理器
        scoreManager = new ScoreManager(GameMainActivity.sGame.getContext());
        
        // 准备显示文本
        prepareDisplayTexts();
        
        // 初始化按钮 - 调整布局增加设置按钮
        playBtn = new UIButton(280, 200, 412, 259, Assets.start, Assets.startDown);
        scoreBtn = new UIButton(280, 270, 412, 329, Assets.score, Assets.scoreDown);  
        settingsBtn = new UIButton(450, 200, 582, 259, Assets.score, Assets.scoreDown); // 复用得分按钮样式
        
        // 启动入场动画
        startEntranceAnimations();
    }

    @Override
    public void update(float delta) {
        // 更新原有跑步动画
        Assets.runAnim.update(delta);
        
        // 更新视觉效果动画
        updateVisualEffects(delta);
        
        // 更新UI动画
        if (animationsEnabled) {
            if (entranceAnimations != null && entranceAnimations.isRunning()) {
                entranceAnimations.update(delta);
            }
            
            if (currentClickAnimation != null && currentClickAnimation.isRunning()) {
                currentClickAnimation.update(delta);
            }
        }
    }

    @Override
    public void render(Painter g) {
        // 渲染增强背景
        renderEnhancedBackground(g);
        
        // 渲染标题区域
        renderTitleSection(g);
        
        // 渲染快速统计
        if (showQuickStats) {
            renderQuickStats(g);
        }
        
        // 渲染按钮
        renderButtons(g);
        
        // 渲染跑步小人装饰
        renderRunningDecorations(g);
    }

    @Override
    public boolean onTouch(MotionEvent e, int scaleX, int scaleY) {
        if ((e.getAction() == MotionEvent.ACTION_DOWN)){
            playBtn.onTouchDown(scaleX, scaleY);
            scoreBtn.onTouchDown(scaleX, scaleY);
            settingsBtn.onTouchDown(scaleX, scaleY);
            
            // 添加点击动画反馈
            if (animationsEnabled) {
                if (playBtn.isPressed(scaleX, scaleY)) {
                    startClickFeedback(playBtn);
                } else if (scoreBtn.isPressed(scaleX, scaleY)) {
                    startClickFeedback(scoreBtn);
                } else if (settingsBtn.isPressed(scaleX, scaleY)) {
                    startClickFeedback(settingsBtn);
                }
            }
            
        } else if ((e.getAction() == MotionEvent.ACTION_UP)){
            if(playBtn.isPressed(scaleX, scaleY)){
                playBtn.cancel();
                onPlayButtonClicked();
            } else if(scoreBtn.isPressed(scaleX, scaleY)){
                scoreBtn.cancel();
                onScoreButtonClicked();
            } else if(settingsBtn.isPressed(scaleX, scaleY)){
                settingsBtn.cancel();
                onSettingsButtonClicked();
            } else {
                playBtn.cancel();
                scoreBtn.cancel();
                settingsBtn.cancel();
            }
        }
        return true;
    }
    
    /**
     * 准备显示文本
     */
    private void prepareDisplayTexts() {
        highScoreText = "最高分: " + scoreManager.getHighScore();
        totalGamesText = "总游戏: " + scoreManager.getTotalGames() + " 次";
        playerLevelText = "等级: Lv." + scoreManager.getPlayerLevel();
        
        // 生成欢迎信息
        if (scoreManager.getTotalGames() == 0) {
            welcomeMessage = "欢迎来到 EllioAndroid!";
        } else if (scoreManager.getPlayerLevel() >= 5) {
            welcomeMessage = "欢迎回来，跑酷大师!";
        } else {
            welcomeMessage = "继续挑战更高分数!";
        }
    }
    
    /**
     * 更新视觉效果
     */
    private void updateVisualEffects(float delta) {
        titlePulse += delta * 2;
        backgroundWave += delta * 0.8f;
        buttonGlow += delta * 3;
    }
    
    /**
     * 渲染增强背景
     */
    private void renderEnhancedBackground(Painter g) {
        // 渲染原始背景
        g.drawImage(Assets.welcome, 0, 0);
        
        // 添加动态渐变层
        float waveAlpha = (float) Math.sin(backgroundWave) * 0.15f + 0.85f;
        g.setColor(Color.argb((int)(30 * waveAlpha), 0, 100, 200));
        g.fillRect(0, 0, GameMainActivity.GAME_WIDTH, GameMainActivity.GAME_HEIGHT);
        
        // 添加顶部信息条背景
        g.setColor(Color.argb(120, 0, 0, 0));
        g.fillRect(0, 0, GameMainActivity.GAME_WIDTH, 80);
    }
    
    /**
     * 渲染标题区域
     */
    private void renderTitleSection(Painter g) {
        // 主标题带脉动效果
        float titleScale = 1.0f + (float) Math.sin(titlePulse) * 0.08f;
        
        // 标题阴影
        g.setColor(Color.argb(100, 0, 0, 0));
        g.drawString("EllioAndroid", 352, 42);
        
        // 主标题
        g.setColor(Color.rgb(255, 215, 0)); // 金色
        g.drawString("EllioAndroid", 350, 40);
        
        // 副标题
        g.setColor(Color.WHITE);
        g.drawString("跑酷冒险游戏", 355, 65);
    }
    
    /**
     * 渲染快速统计
     */
    private void renderQuickStats(Painter g) {
        // 统计信息背景框
        g.setColor(Color.argb(80, 255, 255, 255));
        g.fillRect(50, 90, 300, 80);
        
        g.setColor(Color.WHITE);
        g.drawString("游戏统计", 70, 110);
        
        // 统计数据
        g.setColor(Color.YELLOW);
        g.drawString(highScoreText, 70, 130);
        
        g.setColor(Color.CYAN);
        g.drawString(totalGamesText, 70, 150);
        
        g.setColor(Color.rgb(144, 238, 144)); // 浅绿色
        g.drawString(playerLevelText, 220, 130);
        
        // 欢迎信息
        g.setColor(Color.WHITE);
        g.drawString(welcomeMessage, 380, 100);
    }
    
    /**
     * 渲染按钮
     */
    private void renderButtons(Painter g) {
        // 渲染按钮发光效果
        if (animationsEnabled) {
            renderButtonGlowEffect(g);
        }
        
        // 渲染按钮
        playBtn.render(g);
        scoreBtn.render(g);
        settingsBtn.render(g);
        
        // 按钮标签
        g.setColor(Color.WHITE);
        g.drawString("开始游戏", 310, 250);
        g.drawString("游戏统计", 310, 320);
        g.drawString("设置", 485, 250);
    }
    
    /**
     * 渲染按钮发光效果
     */
    private void renderButtonGlowEffect(Painter g) {
        float glowIntensity = (float) Math.sin(buttonGlow) * 0.3f + 0.7f;
        int glowAlpha = (int) (50 * glowIntensity);
        
        g.setColor(Color.argb(glowAlpha, 255, 215, 0));
        // 为开始按钮添加发光
        g.fillRect((int)playBtn.getX() - 5, (int)playBtn.getY() - 5, 
                  playBtn.getWidth() + 10, playBtn.getHeight() + 10);
    }
    
    /**
     * 渲染跑步小人装饰
     */
    private void renderRunningDecorations(Painter g) {
        // 在不同位置渲染跑步动画作为装饰
        Assets.runAnim.render(g, 50, 200);
        Assets.runAnim.render(g, 650, 180);
        Assets.runAnim.render(g, 600, 350);
    }
    
    /**
     * 开始按钮点击处理
     */
    private void onPlayButtonClicked() {
        Log.d("MenuState", "点击了开始按钮，跳转到难度选择");
        Assets.playSound(Assets.startId);
        setCurrState(new DifficultySelectState());
    }
    
    /**
     * 得分按钮点击处理
     */
    private void onScoreButtonClicked() {
        Log.d("MenuState", "点击了得分按钮，跳转到统计界面");
        Assets.playSound(Assets.startId);
        setCurrState(new ScoreState());
    }
    
    /**
     * 设置按钮点击处理
     */
    private void onSettingsButtonClicked() {
        Log.d("MenuState", "点击了设置按钮");
        Assets.playSound(Assets.startId);
        
        // 简单的设置功能：切换统计显示
        showQuickStats = !showQuickStats;
        
        // 可以扩展为完整的设置界面
        // setCurrState(new SettingsState());
    }
    
    /**
     * 启动入场动画
     */
    private void startEntranceAnimations() {
        if (!animationsEnabled) {
            return;
        }
        
        try {
            // 初始设置按钮为透明状态
            playBtn.setAlpha(0f);
            scoreBtn.setAlpha(0f);
            settingsBtn.setAlpha(0f);
            
            // 设置初始位置（从下方滑入）
            float playBtnOriginalY = playBtn.getY();
            float scoreBtnOriginalY = scoreBtn.getY();
            float settingsBtnOriginalY = settingsBtn.getY();
            
            playBtn.setY(playBtnOriginalY + 50);
            scoreBtn.setY(scoreBtnOriginalY + 80);
            settingsBtn.setY(settingsBtnOriginalY + 50);
            
            // 创建入场动画
            UIAnimator playBtnFadeIn = UIAnimations.fadeIn(playBtn, 0.8f).setStartDelay(0.2f);
            UIAnimator playBtnSlideIn = UIAnimations.animate(playBtn, "y", playBtnOriginalY + 50, playBtnOriginalY, 0.6f, Tween.EASE_OUT).setStartDelay(0.2f);
            
            UIAnimator scoreBtnFadeIn = UIAnimations.fadeIn(scoreBtn, 0.8f).setStartDelay(0.4f);
            UIAnimator scoreBtnSlideIn = UIAnimations.animate(scoreBtn, "y", scoreBtnOriginalY + 80, scoreBtnOriginalY, 0.6f, Tween.EASE_OUT).setStartDelay(0.4f);
            
            UIAnimator settingsBtnFadeIn = UIAnimations.fadeIn(settingsBtn, 0.8f).setStartDelay(0.3f);
            UIAnimator settingsBtnSlideIn = UIAnimations.animate(settingsBtn, "y", settingsBtnOriginalY + 50, settingsBtnOriginalY, 0.6f, Tween.EASE_OUT).setStartDelay(0.3f);
            
            // 组合动画
            entranceAnimations = new AnimationSet(AnimationSet.TOGETHER)
                .addAnimation(playBtnFadeIn)
                .addAnimation(playBtnSlideIn)
                .addAnimation(scoreBtnFadeIn)
                .addAnimation(scoreBtnSlideIn)
                .addAnimation(settingsBtnFadeIn)
                .addAnimation(settingsBtnSlideIn)
                .setAnimationSetListener(new AnimationSet.AnimationSetListener() {
                    @Override
                    public void onAnimationSetEnd(AnimationSet animationSet) {
                        Log.d("MenuState", "增强版主菜单入场动画完成");
                    }
                });
                
            entranceAnimations.start();
            
        } catch (Exception e) {
            // 动画失败时降级到无动画模式
            Log.w("MenuState", "入场动画启动失败，关闭动画: " + e.getMessage());
            animationsEnabled = false;
            // 确保按钮可见
            playBtn.setAlpha(1f);
            scoreBtn.setAlpha(1f);
            settingsBtn.setAlpha(1f);
        }
    }
    
    /**
     * 启动点击反馈动画
     */
    private void startClickFeedback(UIButton button) {
        if (!animationsEnabled) {
            return;
        }
        
        try {
            // 停止之前的点击动画
            if (currentClickAnimation != null && currentClickAnimation.isRunning()) {
                currentClickAnimation.stop();
            }
            
            // 创建增强的点击反馈动画
            currentClickAnimation = new UIAnimator(button)
                .animate("scaleX", 1f, 0.92f, 0.08f, Tween.EASE_OUT)
                .animate("scaleY", 1f, 0.92f, 0.08f, Tween.EASE_OUT)
                .setAnimationListener(new UIAnimator.AnimationListener() {
                    @Override
                    public void onAnimationEnd(UIAnimator animator) {
                        // 恢复原始尺寸，带回弹效果
                        new UIAnimator(button)
                            .animate("scaleX", 0.92f, 1.05f, 0.1f, Tween.EASE_OUT)
                            .animate("scaleY", 0.92f, 1.05f, 0.1f, Tween.EASE_OUT)
                            .setAnimationListener(new UIAnimator.AnimationListener() {
                                @Override
                                public void onAnimationEnd(UIAnimator animator) {
                                    // 最终回到正常大小
                                    button.setScaleX(1f);
                                    button.setScaleY(1f);
                                }
                            })
                            .start();
                    }
                });
                
            currentClickAnimation.start();
            
        } catch (Exception e) {
            Log.w("MenuState", "点击反馈动画失败: " + e.getMessage());
            // 确保按钮处于正常状态
            button.setScaleX(1f);
            button.setScaleY(1f);
        }
    }
    
    /**
     * 获取得分管理器（用于其他状态访问统计数据）
     */
    public ScoreManager getScoreManager() {
        return scoreManager;
    }
}
